package com.campfire.intelligentsecurity.business.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.campfire.intelligentsecurity.business.bean.BusCameraAllow;
import com.campfire.intelligentsecurity.business.bean.BusCameraPlan;
import com.campfire.intelligentsecurity.sys.service.BaseService;
import com.github.drinkjava2.jsqlbox.DbContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import static com.github.drinkjava2.jsqlbox.DB.par;

@Service
public class CameraPlanService extends BaseService {
    @Autowired
    @Qualifier("main")
    DbContext dbContext;

    public Object List() {
        StringBuffer sb = new StringBuffer();
        sb.append(" SELECT");
        sb.append(" b1.id id,");
        sb.append(" b1.camera_num cameraNum,");
        sb.append(" b2.camera_name cameraName,");
        sb.append(" b1.`begin` begin,");
        sb.append(" b1.`end` end,");
        sb.append(" b1.t1 t1,");
        sb.append(" b1.t2 t2,");
        sb.append(" b1.t3 t3 ");
        sb.append(" FROM");
        sb.append(" bus_camera_plan b1");
        sb.append(" LEFT JOIN bus_camera b2 ON b2.camera_num = b1.camera_num ");
        sb.append(" where 1=1 ");
        return builder(sb.toString());
    }

    public Object saveOrUpdate(BusCameraPlan plan) {
        if (plan.getId()!=null){
            plan.setCameraNum(plan.getSelect());
            plan.update();
        }else{
            dbContext.exe("delete from bus_camera_plan where camera_num in('" + plan.getSelect().replaceAll(",", "','") + "')");
            String[] cameraArr=plan.getSelect().split(",");
            BusCameraPlan bean = plan;
            for (String cameraNum:cameraArr){
                bean.setCameraNum(cameraNum);
                bean.insert();
            }
        }
        return true;
    }

    public Object remove(String id) {
        return dbContext.exe("delete from bus_camera_plan where id in('" + id.replaceAll(",", "','") + "')");
    }

    public Object load(String id) {
        if (StrUtil.isNotEmpty(id)) {
            StringBuffer sb = new StringBuffer();
            sb.append(" SELECT id, camera_num, DATE_FORMAT(`begin`,'%Y-%m-%d %H:%i:%s') `begin`,DATE_FORMAT(`end`,'%Y-%m-%d %H:%i:%s') `end`, t1, t2, t3 FROM bus_camera_plan where id=?");
            return dbContext.qryMap(sb.toString(), par(id));
        } else {
            return null;
        }
    }
}
